package com.kejizhentan.springboot2thymeleaf.controller;

import com.kejizhentan.springboot2thymeleaf.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

@Controller
public class IndexController {
    /**
     * @Auther: kejizhentan
     * @Date 2022/4/17 18:22
     * @Description: 来到登录页
     */
    @GetMapping(value = {"/","/login"})
    public String loginPage(){
        return "login";
    }

    @PostMapping("/login")
    public String indexPage(User user, HttpSession session, Model model){
        if(StringUtils.hasLength(user.getUsername()) && "123456".equals(user.getPassword())){
            //把登录成功的用户保存起来
            session.setAttribute("loginUser",user);
            //登录成功重定向到main.html(通过重定向防止表单重复提交)
            return "redirect:/main.html";
        }else {
            model.addAttribute("msg","账号或者密码错误");
            //返回到登录页面
            return "login";
        }

    }

    /**
     * @descrition： 去main页面
     * @auther: kejizhentan
     * @date: 2022/4/17 18:31
     */
    @GetMapping("/main.html")
    public String mainPage(HttpSession session,Model model){
        //是否登录 拦截器/过滤器
        User loginUser = (User) session.getAttribute("loginUser");
        if(loginUser != null){
            return "main";
        }else {
            //回到登录界面
            model.addAttribute("msg","请重新登录");
            return "login";
        }
    }
}
